/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.business.account.core.service.processor.active;

import cn.hutool.core.lang.Assert;
import info.peigen.hotpot.business.account.core.domain.account.Account;
import info.peigen.hotpot.business.account.core.service.processor.base.AbstractAccountServiceProcessor;
import info.peigen.hotpot.business.account.facade.order.edit.EditAccountOrder;
import info.peigen.hotpot.business.account.facade.order.freeze.FreezeAccountOrder;
import info.peigen.hotpot.business.account.facade.order.freeze.FreezeAmountOrder;
import info.peigen.hotpot.business.account.facade.order.freeze.UnfreezeAccountOrder;
import info.peigen.hotpot.business.account.facade.order.freeze.UnfreezeAmountOrder;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.ServiceOrderBase;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import org.noear.solon.annotation.Component;


/**
 * <b>(ActiveAccountProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/5/26
 */
@SuppressWarnings("rawtypes")
@Component
public class ActiveAccountProcessor extends AbstractAccountServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 11;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        String  accountId = switchAccountId(serviceContext);
        Account account   = accountRepository.lock(accountId);
        Assert.notNull(account, () -> new BusinessException(ResultCode.FAILURE, "未能锁定账户[accountId=" + accountId + "]"));
        account.check();
        serviceContext.setDomain(account);
    }

    private String switchAccountId(ProcessorServiceContext serviceContext) {
        ServiceOrderBase order = serviceContext.getOrder();
        if (order instanceof FreezeAccountOrder) {
            return ((FreezeAccountOrder) order).getAccountId();
        } else if (order instanceof UnfreezeAccountOrder) {
            return ((UnfreezeAccountOrder) order).getAccountId();
        } else if (order instanceof FreezeAmountOrder) {
            return ((FreezeAmountOrder) order).getAccountId();
        } else if (order instanceof UnfreezeAmountOrder) {
            return ((UnfreezeAmountOrder) order).getAccountId();
        } else if (order instanceof EditAccountOrder) {
            return ((EditAccountOrder) order).getAccountId();
        } else {
            return null;
        }
    }
}
